package com.xiaocg.base.lock;


import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author xiaocg
 * 读写锁
 */
public class ReadWriteLockDemo {
    public static void main(String[] args)throws Exception {
        CacheTest test = new CacheTest();
        test.getCache().clear();
        for (int i = 0; i < 5; i++) {
            final int num = i;
            new Thread(()->{
                    test.put(num+"",num);
            },String.valueOf(i)).start();
        }

        TimeUnit.MICROSECONDS.sleep(3000);

        for (int i = 0; i < 5; i++) {
            final int a =i;
            new Thread(()->{
                test.get(a+"");
            },String.valueOf(i)).start();

        }

        ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();
        ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();
        writeLock.lock();
        System.out.println("开始写");
        readLock.lock();
        System.out.println("开始读");
        writeLock.unlock();
        readLock.unlock();


    }
}
class CacheTest{
    private  volatile Map<String,Object> cache = new HashMap<>();

    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    public Map<String, Object> getCache() {
        return cache;
    }

    public void put(String key, Object value){
        rwLock.writeLock().lock();
        System.out.println("write:"+rwLock.isWriteLocked());
        try {
            cache.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写完了:::"+key);
        }catch (Exception e){
        }finally {
            rwLock.writeLock().unlock();
        }
    }

    public Object get(String key){
        rwLock.readLock().lock();
        System.out.println("write:"+rwLock.isWriteLocked());
        Object ob = null;
        try {
            ob = cache.get(key);
            System.out.println(Thread.currentThread().getName()+"读完了:::"+key);
        }catch (Exception e){
        }finally {
            rwLock.readLock().unlock();
        }
        return ob;
    }
}